<template>
  <div class="bookshelf-page tomato-mobile">
    <!-- 书架头部 -->
    <div class="bookshelf-header">
      <h1 class="page-title">我的书架</h1>
      <div class="header-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索书架中的小说..."
          clearable
          style="width: 300px;"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>
    
    <!-- 书架内容 -->
    <div class="bookshelf-content" v-loading="loading">
      <!-- 空状态 -->
      <div v-if="filteredBooks.length === 0 && !loading" class="empty-state">
        <div class="empty-icon">
          <el-icon size="64"><Reading /></el-icon>
        </div>
        <h3>书架空空如也</h3>
        <p>去<router-link to="/">首页</router-link>看看有什么好书吧</p>
      </div>
      
      <!-- 书籍列表 -->
      <div v-else class="book-list">
        <div 
          v-for="item in filteredBooks" 
          :key="item.id"
          class="book-item"
        >
          <!-- 小说封面 -->
          <div class="book-cover" @click="goToNovel(item.novel)">
            <img :src="item.novel.cover" :alt="item.novel.title" />
          </div>
          
          <!-- 小说信息 -->
          <div class="book-info">
            <h3 class="book-title" @click="goToNovel(item.novel)">{{ item.novel.title }}</h3>
            <p class="book-author">{{ item.novel.author }}</p>
            <p class="book-latest">
              最新章节：{{ item.novel.lastChapterTitle || '暂无更新' }}
            </p>
            <p class="book-update-time">
              更新时间：{{ formatTime(item.novel.updatedAt) }}
            </p>
          </div>
          
          <!-- 操作按钮 -->
          <div class="book-actions">
            <el-button 
              type="primary" 
              size="small"
              @click="continueReading(item)"
            >
              阅读
            </el-button>
            <el-button 
              size="small"
              @click="removeFromBookshelf(item)"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Reading } from '@element-plus/icons-vue'
import type { BookshelfItem, Novel } from '@/types'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')

// 计算属性
const filteredBooks = computed(() => {
  let books = userStore.bookshelf

  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    books = books.filter(item => 
      item.novel.title.toLowerCase().includes(keyword) ||
      item.novel.author.toLowerCase().includes(keyword)
    )
  }

  // 按最近阅读时间排序
  return books.sort((a, b) => {
    return new Date(b.lastReadTime || b.updatedAt).getTime() - new Date(a.lastReadTime || a.updatedAt).getTime()
  })
})

// 方法
const goToNovel = (novel: Novel) => {
  router.push(`/novel/${novel.id}`)
}

const continueReading = (item: BookshelfItem) => {
  if (item.lastReadChapterId) {
    // 继续上次阅读的章节
    router.push(`/reader/${item.novelId}/${item.lastReadChapterId}`)
  } else {
    // 没有阅读记录，从第一章开始
    router.push(`/reader/${item.novelId}/1`)
  }
}

const removeFromBookshelf = async (item: BookshelfItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要将《${item.novel.title}》移出书架吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const success = await userStore.removeFromBookshelf({ novelId: item.novelId })
    if (success) {
      ElMessage({
        message: '已移出书架',
        type: 'success',
        duration: 2000,
        showClose: true
      })
    } else {
      ElMessage({
        message: '删除失败',
        type: 'error',
        duration: 3000,
        showClose: true
      })
    }
  } catch {
    // 用户取消
  }
}

const formatTime = (timeStr: string) => {
  const date = new Date(timeStr)
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit',
    second: '2-digit'
  })
}

// 生命周期
onMounted(async () => {
  if (userStore.isLoggedIn) {
    loading.value = true
    await userStore.fetchBookshelf()
    loading.value = false
  }
})
</script>

<style lang="scss" scoped>
.bookshelf-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20px;
}

.bookshelf-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  
  .page-title {
    color: #333;
    font-size: 24px;
    font-weight: 600;
    margin: 0;
  }
}

.bookshelf-content {
  min-height: 400px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
  color: #666;
  
  .empty-icon {
    margin-bottom: 20px;
    color: #ccc;
  }
  
  h3 {
    margin-bottom: 10px;
    color: #666;
  }
  
  a {
    color: #007bff;
    text-decoration: none;
    
    &:hover {
      text-decoration: underline;
    }
  }
}

.book-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.book-item {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 15px;
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }
  
  .book-cover {
    flex-shrink: 0;
    width: 60px;
    height: 80px;
    cursor: pointer;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 4px;
    }
  }
  
  .book-info {
    flex: 1;
    min-width: 0;
    
    .book-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin: 0 0 8px 0;
      cursor: pointer;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      
      &:hover {
        color: #007bff;
      }
    }
    
    .book-author {
      color: #666;
      font-size: 14px;
      margin: 0 0 8px 0;
    }
    
    .book-latest {
      color: #666;
      font-size: 13px;
      margin: 0 0 5px 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .book-update-time {
      color: #999;
      font-size: 12px;
      margin: 0;
    }
  }
  
  .book-actions {
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    gap: 8px;
    align-self: flex-start;
    width: 60px;
    
    .el-button {
      width: 100%;
      height: 32px;
      margin: 0;
      padding: 0;
      text-align: center;
      box-sizing: border-box;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .bookshelf-page {
    padding: 15px;
  }
  
  .bookshelf-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
    
    .header-actions {
      .el-input {
        width: 100% !important;
      }
    }
  }
  
  .book-list {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .book-item {
    padding: 15px;
    
    .book-actions {
      flex-direction: row;
      align-self: flex-end;
      
      .el-button {
        width: auto;
        padding: 5px 12px;
      }
    }
  }
}

/* =============== 番茄风格移动端优化 =============== */
@media (max-width: 768px) {
  .bookshelf-page.tomato-mobile {
    background: var(--tomato-background);
    padding: var(--tomato-space-lg);
    
    .bookshelf-header {
      background: var(--tomato-card-bg);
      border-radius: var(--tomato-radius-large);
      box-shadow: var(--tomato-shadow-card);
      padding: var(--tomato-space-xl);
      margin-bottom: var(--tomato-space-xl);
      
      .page-title {
        font-size: 24px;
        font-weight: 700;
        color: var(--tomato-text-primary);
        margin-bottom: var(--tomato-space-md);
      }
      
      .header-actions {
        .el-input {
          .el-input__wrapper {
            border-radius: var(--tomato-radius-medium);
            border: 2px solid var(--tomato-border);
            transition: var(--tomato-transition);
            
            &:hover {
              border-color: var(--tomato-primary);
            }
            
            &.is-focus {
              border-color: var(--tomato-primary);
              box-shadow: 0 0 0 4px rgba(255, 107, 53, 0.1);
            }
          }
        }
      }
    }
    
    .bookshelf-content {
             .empty-state {
         background: var(--tomato-card-bg);
         border-radius: var(--tomato-radius-large);
         box-shadow: var(--tomato-shadow-card);
         border: 1px solid var(--tomato-border);
         transition: var(--tomato-transition);
         padding: var(--tomato-space-3xl);
         text-align: center;
        
        .empty-icon {
          margin-bottom: var(--tomato-space-xl);
          color: var(--tomato-text-disabled);
        }
        
        h3 {
          font-size: 18px;
          font-weight: 600;
          color: var(--tomato-text-primary);
          margin-bottom: var(--tomato-space-md);
        }
        
        p {
          color: var(--tomato-text-secondary);
          font-size: 14px;
          
          a {
            color: var(--tomato-primary);
            text-decoration: none;
            font-weight: 600;
            
            &:hover {
              text-decoration: underline;
            }
          }
        }
      }
      
      .book-list {
        display: flex;
        flex-direction: column;
        gap: var(--tomato-space-md);
        
                 .book-item {
           background: var(--tomato-card-bg);
           border-radius: var(--tomato-radius-large);
           box-shadow: var(--tomato-shadow-card);
           border: 1px solid var(--tomato-border);
           transition: var(--tomato-transition);
           padding: var(--tomato-space-lg);
           display: flex;
           gap: var(--tomato-space-lg);
           margin-bottom: 0;
           
           &:hover {
             background: var(--tomato-background);
             box-shadow: var(--tomato-shadow-popup);
             transform: translateY(-2px);
           }
          
          &:active {
            transform: scale(0.98);
          }
          
          .book-cover {
            width: 80px;
            height: 100px;
            border-radius: var(--tomato-radius-medium);
            overflow: hidden;
            flex-shrink: 0;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            cursor: pointer;
            transition: var(--tomato-transition);
            
            &:hover {
              transform: scale(1.05);
            }
            
            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }
          
          .book-info {
            flex: 1;
            min-width: 0;
            
            .book-title {
              font-size: 16px;
              font-weight: 700;
              color: var(--tomato-text-primary);
              margin-bottom: var(--tomato-space-xs);
              cursor: pointer;
              transition: var(--tomato-transition);
              
              // 限制行数
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
              overflow: hidden;
              
              &:hover {
                color: var(--tomato-primary);
              }
            }
            
            .book-author {
              font-size: 12px;
              color: var(--tomato-text-secondary);
              margin-bottom: var(--tomato-space-sm);
              font-weight: 500;
            }
            
            .book-latest {
              font-size: 12px;
              color: var(--tomato-text-secondary);
              margin-bottom: var(--tomato-space-xs);
              
              // 限制行数
              display: -webkit-box;
              -webkit-line-clamp: 1;
              -webkit-box-orient: vertical;
              overflow: hidden;
            }
            
            .book-update-time {
              font-size: 10px;
              color: var(--tomato-text-disabled);
              margin-bottom: var(--tomato-space-md);
            }
          }
          
          .book-actions {
            display: flex;
            flex-direction: column;
            gap: var(--tomato-space-sm);
            flex-shrink: 0;
            
                         .el-button {
               display: inline-flex;
               align-items: center;
               justify-content: center;
               padding: var(--tomato-space-sm) var(--tomato-space-md);
               border-radius: var(--tomato-radius-medium);
               font-size: 12px;
               font-weight: 600;
               text-decoration: none;
               border: none;
               cursor: pointer;
               transition: var(--tomato-transition);
               min-height: 36px;
               
               &.el-button--primary {
                 background: var(--tomato-primary);
                 color: white;
                 box-shadow: var(--tomato-shadow-button);
                 
                 &:hover {
                   background: var(--tomato-primary-dark);
                   transform: translateY(-1px);
                 }
                 
                 &:active {
                   transform: translateY(0);
                 }
               }
               
               &.el-button--default {
                 background: var(--tomato-card-bg);
                 color: var(--tomato-text-primary);
                 border: 1px solid var(--tomato-border);
                 
                 &:hover {
                   border-color: var(--tomato-primary);
                   color: var(--tomato-primary);
                 }
               }
             }
          }
        }
      }
    }
  }
}

@media (max-width: 480px) {
  .bookshelf-page.tomato-mobile {
    padding: var(--tomato-space-md);
    
    .bookshelf-header {
      padding: var(--tomato-space-lg);
      
      .page-title {
        font-size: 20px;
      }
      
      .header-actions {
        margin-top: var(--tomato-space-md);
        
        .el-input {
          width: 100% !important;
        }
      }
    }
    
    .book-list {
      .book-item {
        padding: var(--tomato-space-md);
        gap: var(--tomato-space-md);
        
        .book-cover {
          width: 60px;
          height: 80px;
        }
        
        .book-info {
          .book-title {
            font-size: 14px;
          }
        }
        
        .book-actions {
          .el-button {
            font-size: 12px;
            padding: var(--tomato-space-xs) var(--tomato-space-sm);
          }
        }
      }
    }
  }
}
</style> 